#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : booktj_modules.py
# @Author: Xuhao
# @Date  : 2018/4/13
# @Desc  : 

from app.Sql.SQLSession import Base,DataBaseConnector
from app.Modules.book_modules import NoverInfo
from app.Modules.rankList_modules import RankList
from sqlalchemy import Column, String, Integer
import json
from sqlalchemy.ext.declarative import DeclarativeMeta
from sqlalchemy.sql.expression import func



# 经典推荐
class BookJinDian(Base):
    '''
    经典推荐, 包括 男生，女生的经典热门书籍推荐
    '''
    __tablename__ = 'book_jinpin'
    __table_args__ = {"extend_existing": True}

    bookID = Column(String(32),primary_key=True)
    bookName = Column(String(128))
    index = Column(Integer)

    @classmethod
    def select_JinDian(cls, fl = 0):
        '''
        小说推荐
        fl 0 = 全部， 1 = 男神 ['玄幻魔法', '武侠修真', '网游竞技']  2 = 女神
        :return:
        '''
        connect = DataBaseConnector()

        session = connect.get_session()

        if fl == 0:

            bookinfo = session.query(NoverInfo).join(BookJinDian, NoverInfo.noveID == BookJinDian.bookID).order_by(func.random()).limit(8).all()

            return json.dumps(bookinfo, cls=new_alchemy_encoder(False, 'NoverInfo'))

        elif fl == 1:

            bookinfo = session.query(NoverInfo).join(BookJinDian, NoverInfo.noveID == BookJinDian.bookID).filter(
                NoverInfo.noveCategory.in_(['玄幻魔法', '武侠修真', '科幻小说', '网游动漫','历史军事', '侦探推理', '穿越小说'])).order_by(func.random()).limit(8).all()

            return json.dumps(bookinfo, cls=new_alchemy_encoder(False, 'NoverInfo'))

        else:

            bookinfo = session.query(NoverInfo).join(BookJinDian, NoverInfo.noveID==BookJinDian.bookID).filter(NoverInfo.noveCategory.in_(['都市言情', '其他类型', '散文诗词', '散文诗词','恐怖灵异'])).order_by(func.random()).limit(8).all()

            return json.dumps(bookinfo, cls=new_alchemy_encoder(False, 'NoverInfo'))



# 男神推荐
class BookBoyTuijian(Base):
    __tablename__ = 'book_nanshen'
    __table_args__ = {"extend_existing": True}

    bookID = Column(String(32))
    bookName = Column(String(128))
    index = Column(Integer)
    id = Column(Integer, primary_key=True)

    @classmethod
    def select_BoyJinDian(cls):
        '''
        小说推荐
        :return:
        '''
        connect = DataBaseConnector()

        session = connect.get_session()

        bookinfo = session.query(NoverInfo).join(BookBoyTuijian, NoverInfo.noveID==BookBoyTuijian.bookID).order_by(func.random()).limit(7).all()

        return json.dumps(bookinfo, cls=new_alchemy_encoder(False, 'NoverInfo'))


# 女神推荐
class BookladyTuijian(Base):
    __tablename__ = 'book_nvshen'
    __table_args__ = {"extend_existing": True}

    bookID = Column(String(32))
    bookName = Column(String(128))
    index = Column(Integer)
    id = Column(Integer, primary_key=True)

    @classmethod
    def select_ladyJinDian(cls):
        '''
        小说推荐
        :return:
        '''
        connect = DataBaseConnector()

        session = connect.get_session()

        bookinfo = session.query(NoverInfo).join(BookladyTuijian, NoverInfo.noveID==BookladyTuijian.bookID).order_by(func.random()).limit(7).all()

        return json.dumps(bookinfo, cls=new_alchemy_encoder(False, 'NoverInfo'))



# 连载推荐, 男生，女生
class BooklianzaiTuijian():

    @classmethod
    def select_lianzai(cls, fl = 0):
        '''
        小说推荐
        :return:
        '''
        connect = DataBaseConnector()

        session = connect.get_session()

        if int(fl) == 0:
            bookinfo = session.query(NoverInfo).order_by(
                func.random()).limit(7).all()

            return json.dumps(bookinfo, cls=new_alchemy_encoder(False, 'NoverInfo'))
        elif int(fl) == 1:

            bookinfo = session.query(NoverInfo).filter(
                NoverInfo.noveCategory.in_(['玄幻魔法', '武侠修真', '科幻小说', '网游动漫','历史军事', '侦探推理', '穿越小说'])).order_by(
                func.random()).limit(7).all()

            return json.dumps(bookinfo, cls=new_alchemy_encoder(False, 'NoverInfo'))

        elif int(fl) == 2:

            bookinfo = session.query(NoverInfo).filter(
                NoverInfo.noveCategory.in_(['都市言情', '其他类型', '散文诗词', '散文诗词','恐怖灵异'])).order_by(
                func.random()).limit(7).all()

            return json.dumps(bookinfo, cls=new_alchemy_encoder(False, 'NoverInfo'))


def new_alchemy_encoder(revisit_self=False, fields_to_expand=[]):
    _visited_objs = []

    class AlchemyEncoder(json.JSONEncoder):
        def default(self, obj):
            if isinstance(obj.__class__, DeclarativeMeta):
                # don't re-visit self
                if revisit_self:
                    if obj in _visited_objs:
                        return None
                    _visited_objs.append(obj)

                # go through each field in this SQLalchemy class
                fields = {}
                for field in [x for x in dir(obj) if
                              not x.startswith('_') and x != 'metadata' and hasattr(obj.__getattribute__(x),
                                                                                    '__call__') == False]:
                    val = obj.__getattribute__(field)

                    # is this field another SQLalchemy object, or a list of SQLalchemy objects?
                    if isinstance(val.__class__, DeclarativeMeta) or (
                                    isinstance(val, list) and len(val) > 0 and isinstance(val[0].__class__,
                                                                                          DeclarativeMeta)):
                        # unless we're expanding this field, stop here
                        if field not in fields_to_expand:
                            # not expanding this field: set it to None and continue
                            fields[field] = None
                            continue

                    fields[field] = val
                # a json-encodable dict
                return fields

            return json.JSONEncoder.default(self, obj)

    return AlchemyEncoder

from app.common.pyDbRowFactory import  DbRowFactory
if __name__ == "__main__":

    print(BooklianzaiTuijian.select_JinDian())